/*
 * @Author: your name
 * @Date: 2021-04-07 21:33:48
 * @LastEditTime: 2021-04-08 13:30:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Editif
 * @FilePath: \my-app-koa\client\src\actions\authAction.js
 */
import { GET_ERRORS, SET_CURRENT_USER } from './types'
import axios from 'axios'
import setAuthToken from '../utils/setAuthToken'
import jwt_decode from 'jwt-decode'
export const registerUser = (userData, history) => dispatch => {
    axios.post("/api/users/register", userData)
        .then(res => history.push('/login'))
        .catch(err => dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        }))
}


export const loginUser = (userData) => dispatch => {
    axios.post("/api/users/login", userData)
        .then(res => {
            const { token } = res.data
            localStorage.setItem('jwtToken', token)
            setAuthToken(token)
            const decode = jwt_decode(token)
            dispatch(setCurrentUser(decode));
        })
        .catch(err => dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        }))
}
export const setCurrentUser = decode => {
    return {
        type: SET_CURRENT_USER,
        payload: decode
    }
}

export const logoutUser = () => dispatch => {
    localStorage.removeItem('jwtToken');
    setAuthToken(false)
    dispatch(setCurrentUser({}));
    // axios.post("/api/users/logout")
    //     .then(res => {
    //         if (res.success) {
    //             localStorage.removeItem('jwtToken');
    //             setAuthToken(false)
    //             dispatch(setCurrentUser({}));
    //         }
    //     })
    //     .catch(err => dispatch({
    //         type: GET_ERRORS,
    //         payload: err.response.data
    //     }))
}
